package com.lxx.wiki.service;

import com.lxx.wiki.domain.entity.*;
import com.lxx.wiki.domain.req.DocSaveReq;
import com.lxx.wiki.domain.resp.CategoryQueryResp;
import com.lxx.wiki.domain.resp.DocQueryResp;
import com.lxx.wiki.mapper.ContentMapper;
import com.lxx.wiki.mapper.DocMapper;
import com.lxx.wiki.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DocService {

    @Autowired
    private DocMapper docMapper;

    @Autowired
    private ContentMapper contentMapper;

    public List<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        //  基于sort进行升序排序
        docExample.setOrderByClause("sort asc");
        // 根据ebookId查询
        criteria.andEbookIdEqualTo(ebookId);

        List<Doc> docList = docMapper.selectByExample(docExample);

        List<DocQueryResp> docQueryRespList = BeanCopyUtils.copyBeanList(docList, DocQueryResp.class);
        return docQueryRespList;
    }

    @Transactional
    public void save(DocSaveReq docSaveReq) {
        Doc doc = BeanCopyUtils.copyBean(docSaveReq, Doc.class);
        Content content = BeanCopyUtils.copyBean(docSaveReq, Content.class);

        if (ObjectUtils.isEmpty(doc.getId())) {
            // 新增
            // id数据库设置了自增,主键回填
            docMapper.insert(doc);
            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            // 修改
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    @Transactional
    public void del(String ids) {

        List<Long> list = List.of(ids.split("\\.")).stream().map(item -> Long.parseLong(item)).collect(Collectors.toList());
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(list);
        docMapper.deleteByExample(docExample);

        ContentExample contentExample = new ContentExample();
        ContentExample.Criteria criteria1 = contentExample.createCriteria();
        criteria1.andIdIn(list);
        contentMapper.deleteByExample(contentExample);
    }
}
